package com.example.swimmingpool.service.wx;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.swimmingpool.entity.user.User;
import com.example.swimmingpool.entity.user_auth.UserAuth;
import com.example.swimmingpool.entity.vip.Vip;
import com.example.swimmingpool.mapper.user.UserMapper;
import com.example.swimmingpool.mapper.user_auth.UserAuthMapper;
import com.example.swimmingpool.qo.base.BaseQo;
import com.example.swimmingpool.vo.wx.WxUserVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class WxUserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserAuthMapper userAuthMapper;

    @Resource
    private MongoTemplate mongoTemplate;

    public IPage<WxUserVo> getUser(BaseQo qo) {
        IPage<UserAuth> page = new Page<>(qo.getCurrent(), qo.getSize());
        var pages = new LambdaQueryChainWrapper<>(userAuthMapper).page(page);
        var userIds = pages.getRecords().stream().map(UserAuth::getUserId).toList();
        List<User> users = userMapper.selectBatchIds(userIds);
        Query query = new Query(Criteria.where("userId").in(userIds.stream().map(String::valueOf).toList()));
        List<Vip> vips = mongoTemplate.find(query, Vip.class);
        List<WxUserVo> list = users.stream().map(it -> {
            var tmp = BeanUtil.copyProperties(it, WxUserVo.class);
            tmp.setIsVip(vips.stream().anyMatch(vip -> vip.getUserId().equals(String.valueOf(it.getId()))));
            return tmp;
        }).toList();
        AtomicInteger idx = new AtomicInteger(-1);
        log.info(JSON.toJSONString(list));
        return page.convert(it -> {
            idx.addAndGet(1);
            return list.get(idx.get());
        });

    }
}
